from zope.interface import implements, Interface

from Products.Five import BrowserView
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
from BeautifulSoup import BeautifulSoup as bt
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from zope.component import queryUtility
from zope.i18n.interfaces import ITranslationDomain
from my315ok.products import productsMessageFactory as _


class ImultiproductsView(Interface):
    """
    multiproducts view interface
    """

    def mainimage(self):
        """fetch the product main photo"""
    def auximage(self):
        """fetch attached photo for the product"""
    def parameters(self):
        """fetch product details parameters table"""    
           



class multiproductsView(BrowserView):
    """
    multiproducts browser view
    """
    implements(ImultiproductsView)

    
    def __init__(self, context, request):
        self.context = context
        self.request = request
    
    def fetch_list_position(self,lt,item):
#        import pdb
#        pdb.set_trace()
        if item in lt:
            for i in range(len(lt)):
                if lt[i] == item:
                    break
                else:
                    continue
            return i
        else:
            return 0
                
        
    @property
    def PerPagePrdtNum(self):
        return self.context.getPerPagePrdtNum      

    @memoize
    def prdt_images(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        sepath= '/'.join(self.context.getPhysicalPath()) 
        query = {'meta_type':('product'),
                 'sort_on':'getObjPositionInParent',
                 'sort_order':'forward',
                 'path':sepath,
                 }        
        sd = catalog(query)
        return sd
    
    @memoize
    def img_tag(self,fieldname="image",small="tile",preview="mini",large="large"):
#        import pdb
#        pdb.set_trace()
        imglists = {}
        csmall = []
        cpreview = []
        clargelink = []
        imgviewurl = []
        imgtitle = []
        imgobjs = self.prdt_images()
        num = len(imgobjs)
        if num > 0:            
            for i in imgobjs:

                jt = i._unrestrictedGetObject()
                try:
                    fd = jt.getField(fieldname)
                    tl = jt.Title()
                    csmall.append(fd.tag(jt,scale=small))
                    cpreview.append(fd.tag(jt,scale=preview))
                    clargelink.append(jt.absolute_url() + "/" + fieldname + "_" + large)
                    imgviewurl.append(jt.absolute_url() + "/base_view")
                    imgtitle.append(tl)
                except:
                    continue                
            
        imglists["small"] = csmall
        imglists["preview"] = cpreview
        imglists["large"] = clargelink
        imglists["imgurl"] = imgviewurl
        imglists["title"] = imgtitle
        return imglists
    @memoize
    def img_fast_tag(self,fieldname="image",small="tile",preview="mini",large="large"):
#        import pdb
#        pdb.set_trace()
        imglists = {}
        csmall = []
        cpreview = []
        clargelink = []
        imgviewurl = []
        imgtitle = []
        imgobjs = self.prdt_images()
        num = len(imgobjs)
        if num > 0:            
            for i in imgobjs:            
                try:
#                    base = self.request['ACTUAL_URL']
#                    id = i.getId()
                    objurl = i.getURL()
                    base =  objurl + "/" + fieldname + "_"
                    tl = i.Title
                    surl = base  + small
                    purl = base  + preview
                    lurl = base  + large 
                    simg = "<img src='%s' alt='%s' title='%s' />" % (surl,tl,tl)
                    pimg = "<img src='%s' alt='%s' title='%s' />" % (purl,tl,tl)
#                    limg = "<img src='%s' alt='%s' title='%s' />" % (lurl,tl,tl)
                    imgobjurl = objurl + "/@@product_view"                    
                    csmall.append(simg)
                    cpreview.append(pimg)
                    clargelink.append(lurl)
                    imgviewurl.append(imgobjurl)
                    imgtitle.append(tl)
                except:
                    continue                
            
        imglists["small"] = csmall
        imglists["preview"] = cpreview
        imglists["large"] = clargelink
        imglists["imgurl"] = imgviewurl
        imglists["title"] = imgtitle
        return imglists
    def mainimage(self,fieldname="image"):
#        main = self.img_tag("image")
        main = self.img_fast_tag("image")
        return main
        
    def auximage(self,j):
        aux = self.details(fieldname="text")
        sp = bt(aux["comments"][j])
        try:
            auim = sp("img")[0].__str__()
        except:
            auim = ""
        return auim
        
    def parameters(self,j):
        aux = self.details(fieldname="text")
        sp = bt(aux["comments"][j])
       
        try:
            par = sp("table")[0].__str__()
        except:
            par = ""
        return par
    
    def notes(self,j):
        aux = self.details(fieldname="text")
        sp = bt(aux["comments"][j])
       
        try:
            par = sp.find("div","footer-notes")
            if par ==None:
                par = ""
            else:
                par = par.__str__()
        except:
            par = ""
        return par
        
        
    @memoize
    def details(self,fieldname="text"):
#        import pdb
#        pdb.set_trace()
        imglists = {}
        cpara = []       
        imgobjs = self.prdt_images()
        num = len(imgobjs)
        if num > 0:            
            for i in imgobjs:
                jt = i.getObject()
                try:
                    fd = jt.getText()
                    cpara.append(fd)                            
                except:
                    continue                
            
        imglists["comments"] = cpara        
        return imglists
     
   


class simpleview(multiproductsView):
    """A simple view layout."""    
    
class kuputabsview(multiproductsView):
    """A kuputabs view layout.""" 
    
    def parameters(self,j):
        aux = self.details(fieldname="text")
        sp = bt(aux["comments"][j])
#        import pdb
#        pdb.set_trace()

        util = queryUtility(ITranslationDomain, 'my315ok.products')
        bn = u"parameters"
        cnc = u"configuration"
        ps = util.translate(bn,target_language="zh",default="parameters")
        cn = util.translate(cnc,target_language="zh",default="configuration")
        try:
            par1 = sp("table")[0].__str__()
        except:
            par1 = ""
        try:
            par2 = sp("table")[1].__str__()
        except:
            par2 = ""
        tabhd1 = "<h2 class='kuputab-tab-definer-default'>" + ps + "</h2>"
        tabhd2 = "<h2 class='kuputab-tab-definer'>" + cn + "</h2>"
        par = tabhd1 + par1 +tabhd2 + par2
       
        return par
    
    
       
        
